import random
import pygame
import sys
from pygame.locals import *

class starfield(object):
    def __init__(self, pos , size, max, speed):
        self.stars = []
        self.pos = pos
        self.size = size
        self.max = max
        self.speed = speed
        self.box = True
        self.color = (255,255,255)
        self.bordercolor = Color(255,255,255)
        self.backgroundcolor = Color(0,0,0)
        for loop in range(0, max):
            star = [random.randrange(0, size[0] - 1),
                    random.randrange(0, size[1] - 1)]
            self.stars.append(star);
    def draw(self, screen):
        if self.box:
             pygame.draw.rect(screen, self.backgroundcolor, Rect(self.pos[0], self.pos[1], self.size[0],self.size[1]), 0)
             pygame.draw.rect(screen, self.bordercolor, Rect(self.pos[0], self.pos[1], self.size[0],self.size[1]), 1)
        for loop in range(0, self.max):
            p = (self.pos[0] + self.stars[loop][0], self.pos[1] + self.stars[loop][1] )
            screen.set_at(p, self.color)
    def update(self):
        for loop in range(0, self.max):
            self.stars[loop][0] += self.speed
            if self.stars[loop][0]>self.size[0]:
                self.stars[loop][0] = 0
            
# DEMO
sf = [starfield( (50,50), (550,410), 80, 1 ),       
      starfield( (50,50), (550,410), 33, 2 ),
      starfield( (50,50), (550,410), 33, 3 ),
      starfield( (50,50), (550,410), 12, 4 )
      ]

sf[3].color = (240,240,240)
sf[2].color = (180,180,180)
sf[1].color = (120,120,120)
sf[0].color = (73,73,73)

for s in sf:
    s.box = False


TIMEREVENT = pygame.USEREVENT
UPDATEEVENT = pygame.USEREVENT+1
FPS = 50
pygame.init()
window = pygame.display.set_mode((640, 480))

background = None
background = pygame.Surface(window.get_size())
background.fill((0, 0, 0))

pygame.time.set_timer(TIMEREVENT, int(1000 / FPS))
pygame.time.set_timer(UPDATEEVENT, 50)

while True:

    for event in pygame.event.get():
        if event.type == TIMEREVENT:
            background.fill((0,0,0))
            for s in sf:
                s.draw(background)
            #Spaceship
            pygame.draw.rect(background, Color(255,155,0), Rect(160, 250, 90,20), 0)
            pygame.draw.rect(background, Color(255,155,0), Rect(200, 250, 20,55), 0)
            pygame.draw.rect(background, Color(255,155,0), Rect(200, 300, 150,25), 0)
            pygame.draw.rect(background, Color(255,155,0), Rect(320, 270, 15,30), 0)
            pygame.draw.rect(background, Color(255,155,0), Rect(300, 260, 75,10), 0)
            window.blit(background, (0, 0))
            pygame.display.flip()
        elif event.type == UPDATEEVENT:
            for s in sf:
                s.update()
        elif event.type == pygame.QUIT:
            sys.exit()
